<?php
namespace app\shop\controller;
use app\ApiRest;
use app\integral\model\IntegralGoods;
use app\member\model\Member;
use app\Rest;
use app\shop\model\AdminGoods;
use app\shop\model\AdminShopSpePrice;
use think\App;
use think\facade\Db;
use think\Request;

use app\shop\model\AdminShopOrder as ShopOderModel;
use app\shop\model\AdminShopOrderRefund;
use app\shop\model\IndexCardCount;
use app\shop\model\AdminSellingWater;
use app\shop\model\AdminSellingProfit;
use app\shop\model\IndexUser;


class IndexCheck extends ApiRest
{

    protected $model;

    protected $spe_price_model;

    protected $goods_model;


    public function __construct(App $app) {

        parent::__construct($app);

        $this->model        = new ShopOderModel();

        $this->model        = new ShopOderModel();

        $this->count_model  = new IndexCardCount();

        $this->refund_model = new AdminShopOrderRefund();

        $this->water_model  = new AdminSellingWater();

        $this->profit_model = new AdminSellingProfit();

        $this->user_model   = new IndexUser();

        $this->spe_price_model =  new AdminShopSpePrice();

        $this->goods_model  = new AdminGoods();

    }
    /**
     * User: chenniang
     * Date: 2019-09-12 18:37
     * @return bool
     * descption:检查订单
     */
    public function checkOrder(){

        $admin_order_model = new \app\shop\model\AdminShopOrder();
        //检测订单
        $admin_order_model->checkOrder($this->_uniacid,$this->_config);

        return true;
    }
    /**
     * User: chenniang
     * Date: 2019-09-12 14:43
     * @return void
     * descption: 检查超时订单
     */
    public function checkOrderTime(){

        $order_overtime  = !empty($this->_config['order_overtime'])?$this->_config['order_overtime']:1800;

        $order_overtime  = time() - $order_overtime;

        $order_dis[] = ['uniacid','=',$this->_uniacid];

        $order_dis[] = ['pay_status','=',0];

        $order_dis[] = ['order_status','<>',1];

        $order_dis[] = ['refund_status','=',0];

        $order_dis[] = ['create_time','<',$order_overtime];

        $order       = Db::name('longbing_card_shop_order')->where($order_dis)->field('id,record_id,collage_id,user_id,type')->select();

        if(!empty($order)){

            foreach ($order as $v){

                Db::startTrans();
                //修改订单状态
                $this->model->orderUpdate(['id'=>$v['id']],['order_status' => 1]);
                //归还优惠券
                if(!empty($v['record_id'])){

                    Db::name('longbing_card_coupon_record')->where(['id'=>$v['record_id']])->update(['status'=>1,'update_time'=>time()]);//恢复优惠券状态
                }
                //修改库存销量
                $res = $this->refundStock($v['id']);

                if($res!=1){

                    Db::rollback();

                    continue;
                }
                //拼团订单
                if($v['type']==1){

                    $user = Db::name('longbing_card_shop_collage_list')->where(['id'=>$v['collage_id']])->value('user_id');

                    Db::name('longbing_card_shop_user_collage')->where(['collage_id'=>$v['collage_id'],'user_id'=>$v['user_id']])->update(['collage_status'=>4]);

                    if($v['user_id']==$user){

                        Db::name('longbing_card_shop_collage_list')->where(['id'=>$v['collage_id']])->update(['status'=>4]);

                    }else{

                        Db::name('longbing_card_shop_collage_list')->where(['id'=>$v['collage_id']])->update(['left_number'=>Db::raw('left_number+1')]);
                    }
                }

                Db::commit();
            }
        }
        return true;
    }
    /**
     * User: chenniang
     * Date: 2019-09-12 18:28
     * @return bool
     * descption:取消超时拼团
     */
    public function checkCollageTime(){
        $collage_overtime = !empty($this->_config['collage_overtime'])?$this->_config['collage_overtime']:3600;
        $collage_overtime = time() - $collage_overtime;
        $collage_status[] = ['collage_status','=',1];
        $collage_status[] = ['uniacid','=',$this->_uniacid];
        $collage_status[] = ['create_time','<',$collage_overtime];
        $collage = Db::name('longbing_card_shop_collage_list')->where($collage_status)->select();
        Db::name('longbing_card_shop_collage_list')->where($collage_status)->update(['collage_status'=>4]);
        if(!empty($collage)){
            foreach ($collage as $value){
                $order = Db::name('longbing_card_shop_order')->where(['collage_id'=>$value['id'],'type'=>1])->field('id,order_status,pay_status')->select();
                Db::name('longbing_card_shop_user_collage')->where(['collage_id' => $value['id']])->update(['collage_status' => 4]);
                if(!empty($order)){
                    foreach ($order as $v){
                        $this->model->orderUpdate(['id'=>$v['id']],['order_status'=>1]);
                        if($v['pay_status']==1){
                            $this->water_model->refundWater(['order_id' => $v['id'], 'waiting'=>1]);
                        }
                    }
                }
            }
        }
        return true;
    }
    /**
     * User: chenniang
     * Date: 2019-09-12 18:28
     * @return bool
     * descption:自动收货
     */
    public function checkSendTime(){
        $receiving = empty($this->_config['receiving'])||$this->_config['receiving']<5?5:$this->_config['receiving'];
        $beginTime = time()-$receiving*86400;
//        $beginTime = time()-600;
        $dis[] = ['uniacid'      ,'=',$this->_uniacid];

        $dis[] = ['pay_status'   ,'=',1];

        $dis[] = ['order_status' ,'=',2];

        $dis[] = ['refund_status','=',0];

        $dis[] = ['update_time'  ,'<',$beginTime];

        $list  = Db::name('longbing_card_shop_order')->where($dis)->field('id')->select();

        if (!empty($list)) {

            foreach ( $list as $index => $item ) {

                $this->model->orderUpdate(['id'=>$item['id']],['order_status'=>3]);

                $this->profitUpdate($item);
                //会员模型
                $member_model = new Member();
                //结算会员的商品的权益
                $member_model->updateMember($item);
            }
        }
        return true;
    }


    /**
     * User: chenniang
     * Date: 2019-09-11 10:35
     * @param $order
     * @return bool
     * descption:修改佣金
     */
    public function profitUpdate($order){
        $list = $this->water_model->where(['order_id' => $order['id'], 'waiting' => 1])->select();
        $res  = $this->water_model->waterUpdate(['order_id' => $order['id'], 'waiting' => 1],['waiting' => 2]);
        if(!empty($list)){
            foreach ($list as $index => $item) {
                $money = $item['price'] * $item['extract'] / 100;
                $money = sprintf("%.2f", $money);
                $profit= $this->profit_model->profitInfo(['user_id' => $item['user_id']]);
                if ($profit) {
                    if ($profit['waiting'] >= $money) {
                        $waiting      = $profit['waiting'] - $money;
                        $total_profit = $profit['total_profit'] + $money;
                        $profit_money = $profit['profit'] + $money;
                        $waiting      = sprintf("%.2f", $waiting);
                    } else {
                        $waiting      = 0;
                        $money        = $profit['waiting'];
                        $total_profit = $profit['total_profit'] + $profit['waiting'];
                        $profit_money = $profit['profit'] + $profit['waiting'];
                    }
                    $total_profit = sprintf("%.2f", $total_profit);
                    $profit_money = sprintf("%.2f", $profit_money);
                    $this->profit_model->profitUpdate(['id' => $profit['id']],['waiting' => $waiting, 'total_profit' => $total_profit, 'profit' => $profit_money]);
                    $this->user_model->userUpdate(['id' => $item['source_id']],['create_money'=>Db::raw("create_money+$money")]);
                }
            }
        }
        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-04 16:51
     * @功能说明:加库存减销量
     */
    public function refundStock($order_id){

        $order_goods = Db::name('longbing_card_shop_order_item')->where(['order_id'=>$order_id])->select();

        $i_goods_model = new IntegralGoods();

        foreach ($order_goods as $v){
            //查询该规格
            $spe = $this->spe_price_model->where(['id'=>$v['spe_price_id']])->find();

            if(!empty($spe)){

                $spe = $spe->toArray();
                //加库存
                $res = $this->spe_price_model->where(['create_time'=>$spe['create_time']])->update(['create_time'=>$spe['create_time']+1,'stock'=>$v['number']+$spe['stock']]);

                if($res!=1){

                    return $res;
                }
                //减销量
                $num = $v['number'];

                $res = $this->goods_model->goodsUpdate(['id'=>$v['goods_id']],['sale_count'=>Db::raw("sale_count-$num")]);

                if($res!=1){

                    return $res;
                }

            }
            //退还积分库存 减去积分销量
            if(!empty($v['integral_goods_id'])){

                $res = $i_goods_model->updateStock($v['integral_goods_id'],$num,0);

                if($res!=1){

                    return $res;

                }

            }

        }

        return 1;
    }




















}
